/**
* @depends jquery.ui.js
*/

(function($) {

	$.widget( 'ui.widget_box_contacts', {
		
		_init: function() {
			
			var $this = this;
			this.element.find( 'h3 a[action=all]' ).click( function() {
				var user_id = $(this).closest( '[user_id]' ).attr( 'user_id' );
				$.contact.all( user_id );
			} );
			
			this._refreshLoop();
		},
		
		_refreshLoop: function() {
			
			var $this = this;
			this.refresh();
			setTimeout( function() {
				$this._refreshLoop();
			}, 60 * 1000 );
		},
		
		refresh: function() {
		
			var $this = this;
			var user_id = this.element.attr( 'user_id' );
			var old_content = this.element.find( '> .Content' );
			$.wajax( 'Widget_Box_Contacts', { id: user_id }, function( json ) {
				if( json.status != 'success' ) {
					return;
				}
				old_content.removeClass( 'Loading' );
				var json = json.content;
				
				var content = $(json.content);
				old_content.replaceWith( content );
				content.widget_box_contacts_content();
				
				var all = $this.element.find( 'h3 a[action=all]' );
				all.html( json.all ? 'See all' : '' );
			} );
		}
		
	} );
	
	$.widget( 'ui.widget_box_contacts_content', {
		
		_init: function() {
			
			this.element.find( '.User' ).widget_box_contacts_user();
			this.element.find( '.Request' ).widget_box_contacts_request();
		}
		
	} );
	
	$.widget( 'ui.widget_box_contacts_user', {
	
		_init: function() {
		
			var $this = this;
		
			this.element.click( function() {
				location.href = $this.element.attr( 'href' );
			} );
		}
	
	} );
	
	$.widget( 'ui.widget_box_contacts_request', {
	
		_init: function() {
		
			var $this = this;
			
			this.element.find( 'p' ).dotify();
			
			var request_id = this.element.attr( 'request_id' );
			
			this.element.find( '.Button' ).click( function() {
				
				$.contact.answer( request_id, function() {
					document.location.reload();
				} );
			} );
		}

	} );
	
})(jQuery);
